package cn.eeepay.framework.service.impl.risk;

import cn.eeepay.framework.dao.risk.TransLimitDao;
import cn.eeepay.framework.db.pagination.Page;
import cn.eeepay.framework.model.UserLoginInfo;
import cn.eeepay.framework.model.risk.TransLimitRule;
import cn.eeepay.framework.model.risk.TransLimitWhite;
import cn.eeepay.framework.service.SysDictService;
import cn.eeepay.framework.service.risk.TransLimitService;
import cn.eeepay.framework.util.ListDataExcelExport;
import cn.eeepay.framework.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("transLimitService")
public class TransLimitServiceImpl implements TransLimitService {

    private static final Logger log = LoggerFactory.getLogger(TransLimitServiceImpl.class);

    @Resource
    private TransLimitDao transLimitDao;
    @Resource
    private SysDictService sysDictService;

    @Override
    public List<TransLimitRule> selectTransLimitRuleList(TransLimitRule info, Page<TransLimitRule> page){
        List<TransLimitRule> list=transLimitDao.selectTransLimitRuleList(info,page);
        for (TransLimitRule t:list){
            if("all".equals(t.getTeamId())){
                t.setTeamName("不限");
            }
            if("all".equals(t.getRulesProvinces())){
                t.setRulesProvinces("不限");
            }
            if("all".equals(t.getRulesCity())){
                t.setRulesCity("不限");
            }
        }
        return list;
    }

    @Override
    public void importTransLimitRuleList(TransLimitRule info, HttpServletResponse response) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss") ;
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        String fileName = "交易限制管理列表"+sdf.format(new Date())+".xlsx" ;
        String fileNameFormat = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        response.setHeader("Content-disposition", "attachment;filename="+fileNameFormat);
        List<Map<String, String>> data = new ArrayList<Map<String,String>>() ;
        List<TransLimitRule> list =transLimitDao.importTransLimitRuleList(info);
        if(list.size()<1){
            Map<String, String> maps = new HashMap<String, String>();
            maps.put("id",null);
            maps.put("teamName",null);
            maps.put("cardType",null);
            maps.put("rulesProvinces",null);
            maps.put("rulesCity",null);
            maps.put("limitAction",null);
            maps.put("status",null);
            maps.put("singleDayAmount",null);
            maps.put("singleCountAmount",null);
            maps.put("singleDaycardAmount",null);
            maps.put("singleDaycardCount",null);
            maps.put("createPerson",null);
            maps.put("createTime", null);
            maps.put("lastUpdateTime", null);
            data.add(maps);
        }else{
            Map<String, String> cardTypeMap = sysDictService.selectMapByKey("CARD_TYPE");
            Map<String, String> statusMap = new HashMap<>();
            statusMap.put("1","开启");
            statusMap.put("0","关闭");
            Map<String, String> limitActionMap = new HashMap<>();
            limitActionMap.put("TRANS","限制交易");
            limitActionMap.put("QUOTA","限制额度");
            for (TransLimitRule or : list) {
                if("all".equals(or.getTeamId())){
                    or.setTeamName("不限");
                }
                if("all".equals(or.getRulesProvinces())){
                    or.setRulesProvinces("不限");
                }
                if("all".equals(or.getRulesCity())){
                    or.setRulesCity("不限");
                }
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("id",StringUtil.filterNull(or.getId()));
                maps.put("teamName",StringUtil.filterNull(or.getTeamName()));
                maps.put("cardType",StringUtil.filterNull(cardTypeMap.get(or.getCardType())));
                maps.put("rulesProvinces",StringUtil.filterNull(or.getRulesProvinces()));
                maps.put("rulesCity",StringUtil.filterNull(or.getRulesCity()));
                maps.put("limitAction",StringUtil.filterNull(limitActionMap.get(or.getLimitAction())));
                maps.put("status",StringUtil.filterNull(statusMap.get(or.getStatus()+"")));
                maps.put("singleDayAmount",or.getSingleDayAmount()==null?"":or.getSingleDayAmount().toString());
                maps.put("singleCountAmount",or.getSingleCountAmount()==null?"":or.getSingleCountAmount().toString());
                maps.put("singleDaycardAmount",or.getSingleDaycardAmount()==null?"":or.getSingleDaycardAmount().toString());
                maps.put("singleDaycardCount",or.getSingleDaycardCount()==null?"":or.getSingleDaycardCount().toString());
                maps.put("createPerson",StringUtil.filterNull(or.getCreatePerson()));
                maps.put("createTime", or.getCreateTime()==null?"":sdf1.format(or.getCreateTime()));
                maps.put("lastUpdateTime", or.getLastUpdateTime()==null?"":sdf1.format(or.getLastUpdateTime()));
                data.add(maps);
            }
        }
        ListDataExcelExport export = new ListDataExcelExport();
        String[] cols = new String[]{"id","teamName","cardType","rulesProvinces","rulesCity","limitAction","status",
                "singleDayAmount","singleCountAmount","singleDaycardAmount","singleDaycardCount",
                "createPerson","createTime","lastUpdateTime"
        };
        String[] colsName = new String[]{"ID","组织","卡类型","省份","城市","业务类型","状态",
                "单日最大交易金额设置(元)","单笔最大交易额设置(元)","单日单卡最大交易额设置(元)","单日单卡最大交易笔数设置(笔)",
                "创建人","创建时间","操作时间"
        };
        OutputStream ouputStream =null;
        try {
            ouputStream=response.getOutputStream();
            export.export(cols, colsName, data, response.getOutputStream());
        }catch (Exception e){
            log.error("交易限制管理列表失败!",e);
        }finally {
            if(ouputStream!=null){
                ouputStream.close();
            }
        }
    }

    @Override
    public TransLimitRule selectTransLimitRuleDetail(Long id){
        return transLimitDao.selectTransLimitRuleDetail(id);
    }

    @Override
    public int addTransLimitRule(TransLimitRule info, Map<String, Object> msg) {
        if(info!=null){
            int num=0;
            UserLoginInfo principal = (UserLoginInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            info.setCreatePerson(principal.getUsername());
            //判断限额
            Map map=transLimitDao.selectMinServiceManageQuota(info.getTeamId(),info.getCardType());
            if(map==null||map.isEmpty()){
                msg.put("status", false);
                msg.put("msg", "无服务参考限额；");
                return num;
            }
            BigDecimal minSingleDayAmount= new BigDecimal(StringUtil.ifEmptyThen(map.get("minSingleDayAmount"),"0"));
            BigDecimal minSingleCountAmount= new BigDecimal(StringUtil.ifEmptyThen(map.get("minSingleCountAmount"),"0"));
            BigDecimal minSingleDaycardAmount= new BigDecimal(StringUtil.ifEmptyThen(map.get("minSingleDaycardAmount"),"0"));
            Integer minSingleDaycardCount= Integer.parseInt(StringUtil.ifEmptyThen(map.get("minSingleDaycardCount"),"0"));
            if("QUOTA".equals(info.getLimitAction())){
                if(info.getSingleDayAmount().compareTo(minSingleDayAmount)>0){
                    msg.put("status", false);
                    msg.put("msg", "单日最大交易金额设置不得高于"+minSingleDayAmount+"元；");
                    return num;
                }
                if(info.getSingleCountAmount().compareTo(minSingleCountAmount)>0){
                    msg.put("status", false);
                    msg.put("msg", "单笔最大交易额设置不得高于"+minSingleCountAmount+"元；");
                    return num;
                }
                if(info.getSingleDaycardAmount().compareTo(minSingleDaycardAmount)>0){
                    msg.put("status", false);
                    msg.put("msg", "单日单卡最大交易额设置不得高于"+minSingleDaycardAmount+"元；");
                    return num;
                }
                if(info.getSingleDaycardCount()>minSingleDaycardCount){
                    msg.put("status", false);
                    msg.put("msg", "单日单卡最大交易笔数设置不得高于"+minSingleDaycardCount+"笔；");
                    return num;
                }
            }
            String cityStr="";
            Map<String, String> cardTypeMap = sysDictService.selectMapByKey("CARD_TYPE");
            String cardTypeStr=cardTypeMap.get(info.getCardType());
            if("0".equals(info.getCardType())){
                cardTypeStr="卡类型"+cardTypeStr;
            }
            if("1".equals(info.getAreaType())){
                //判断卡类型和省市已经存在
                String citys[]=info.getRulesCity().split(",");
                for (String city:citys){
                    if(transLimitDao.selectTransLimitRuleCityCount(city,info.getCardType(),info.getTeamId(),info.getLimitAction())>0){
                        cityStr+=city+"、";
                    }
                }
                if(!"".equals(cityStr)){
                    cityStr=cityStr.substring(0,cityStr.length()-1);
                    msg.put("status", false);
                    msg.put("msg", cityStr+"：已经存在于"+cardTypeStr+"设置中，不能重复配置；");
                    return num;
                }
            }else{
                if(transLimitDao.selectTransLimitRuleCityCount(info.getRulesCity(),info.getCardType(),info.getTeamId(),info.getLimitAction())>0){
                    msg.put("status", false);
                    msg.put("msg", info.getRulesCity()+"：已经存在于"+cardTypeStr+"设置中，不能重复配置；");
                    return num;
                }
            }
            transLimitDao.insertTransLimitRule(info);
            transLimitDao.insertTransLimitRuleLog(info.getId(),"new",principal.getUsername());
            msg.put("status", true);
            msg.put("msg", "新增成功!");
            return num;
        }
        msg.put("status", false);
        msg.put("msg", "操作失败!");
        return 0;
    }

    @Override
    public int updateTransLimitRule(TransLimitRule info, Map<String, Object> msg) {
        if(info!=null){
            int num=0;
            UserLoginInfo principal = (UserLoginInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            //判断限额
            Map map=transLimitDao.selectMinServiceManageQuota(info.getTeamId(),info.getCardType());
            if(map==null||map.isEmpty()){
                msg.put("status", false);
                msg.put("msg", "无服务参考限额；");
                return num;
            }
            BigDecimal minSingleDayAmount= new BigDecimal(StringUtil.ifEmptyThen(map.get("minSingleDayAmount"),"0"));
            BigDecimal minSingleCountAmount= new BigDecimal(StringUtil.ifEmptyThen(map.get("minSingleCountAmount"),"0"));
            BigDecimal minSingleDaycardAmount= new BigDecimal(StringUtil.ifEmptyThen(map.get("minSingleDaycardAmount"),"0"));
            Integer minSingleDaycardCount= Integer.parseInt(StringUtil.ifEmptyThen(map.get("minSingleDaycardCount"),"0"));
            if("QUOTA".equals(info.getLimitAction())){
                if(info.getSingleDayAmount().compareTo(minSingleDayAmount)>0){
                    msg.put("status", false);
                    msg.put("msg", "单日最大交易金额设置不得高于"+minSingleDayAmount+"元；");
                    return num;
                }
                if(info.getSingleCountAmount().compareTo(minSingleCountAmount)>0){
                    msg.put("status", false);
                    msg.put("msg", "单笔最大交易额设置不得高于"+minSingleCountAmount+"元；");
                    return num;
                }
                if(info.getSingleDaycardAmount().compareTo(minSingleDaycardAmount)>0){
                    msg.put("status", false);
                    msg.put("msg", "单日单卡最大交易额设置不得高于"+minSingleDaycardAmount+"元；");
                    return num;
                }
                if(info.getSingleDaycardCount()>minSingleDaycardCount){
                    msg.put("status", false);
                    msg.put("msg", "单日单卡最大交易笔数设置不得高于"+minSingleDaycardCount+"笔；");
                    return num;
                }
            }
            String cityStr="";
            Map<String, String> cardTypeMap = sysDictService.selectMapByKey("CARD_TYPE");
            String cardTypeStr=cardTypeMap.get(info.getCardType());
            if("0".equals(info.getCardType())){
                cardTypeStr="卡类型"+cardTypeStr;
            }
            if("1".equals(info.getAreaType())){

                //判断卡类型和省市已经存在
                String citys[]=info.getRulesCity().split(",");
                for (String city:citys){
                    if(transLimitDao.selectTransLimitRuleCityCountById(city,info.getCardType(),info.getTeamId(),info.getLimitAction(),info.getId())>0){
                        cityStr+=city+"、";
                    }
                }
                if(!"".equals(cityStr)){
                    cityStr=cityStr.substring(0,cityStr.length()-1);
                    msg.put("status", false);
                    msg.put("msg", cityStr+"：已经存在于"+cardTypeStr+"设置中，不能重复配置；");
                    return num;
                }
            }else{
                if(transLimitDao.selectTransLimitRuleCityCountById(info.getRulesCity(),info.getCardType(),info.getTeamId(),info.getLimitAction(),info.getId())>0){
                    msg.put("status", false);
                    msg.put("msg", info.getRulesCity()+"：已经存在于"+cardTypeStr+"设置中，不能重复配置；");
                    return num;
                }
            }
            transLimitDao.updateTransLimitRule(info);
            transLimitDao.insertTransLimitRuleLog(info.getId(),"update",principal.getUsername());
            msg.put("status", true);
            msg.put("msg", "修改成功!");
            return num;
        }
        msg.put("status", false);
        msg.put("msg", "操作失败!");
        return 0;
    }

    @Override
    public int updateTransLimitRuleStatus(Integer status,Long id){
        UserLoginInfo principal = (UserLoginInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int num=transLimitDao.updateTransLimitRuleStatus(status,id);
        transLimitDao.insertTransLimitRuleLog(id,"update",principal.getUsername());
        return num;
    }

    @Override
    public int deleteTransLimitRule(Long id){
        UserLoginInfo principal = (UserLoginInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int num=transLimitDao.deleteTransLimitRule(id);
        transLimitDao.insertTransLimitRuleLog(id,"delete",principal.getUsername());
        return num;
    }

    @Override
    public List<Map> selectTransLimitRuleLog(Long limitRule){
        return transLimitDao.selectTransLimitRuleLog(limitRule);
    }

    @Override
    public List<TransLimitWhite> selectTransLimitWhiteList(TransLimitWhite info, Page<TransLimitWhite> page){
        List<TransLimitWhite> list=transLimitDao.selectTransLimitWhiteList(info,page);
        return list;
    }

    @Override
    public void importTransLimitWhiteList(TransLimitWhite info, HttpServletResponse response) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss") ;
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        String fileName = "交易限制商户白名单列表"+sdf.format(new Date())+".xlsx" ;
        String fileNameFormat = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        response.setHeader("Content-disposition", "attachment;filename="+fileNameFormat);
        List<Map<String, String>> data = new ArrayList<Map<String,String>>() ;
        List<TransLimitWhite> list =transLimitDao.importTransLimitWhiteList(info);
        if(list.size()<1){
            Map<String, String> maps = new HashMap<String, String>();
            maps.put("id",null);
            maps.put("merchantNo",null);
            maps.put("mobilephone",null);
            maps.put("status",null);
            maps.put("limitAction",null);
            maps.put("remark",null);
            maps.put("createPerson",null);
            maps.put("createTime", null);
            data.add(maps);
        }else{
            Map<String, String> statusMap = new HashMap<>();
            statusMap.put("1","开启");
            statusMap.put("0","关闭");
            Map<String, String> limitActionMap = new HashMap<>();
            limitActionMap.put("TRANS","限制交易");
            limitActionMap.put("QUOTA","限制额度");
            for (TransLimitWhite or : list) {
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("id",StringUtil.filterNull(or.getId()));
                maps.put("merchantNo",StringUtil.filterNull(or.getMerchantNo()));
                maps.put("mobilephone",StringUtil.filterNull(or.getMobilephone()));
                maps.put("status",StringUtil.filterNull(statusMap.get(or.getStatus()+"")));
                maps.put("limitAction",StringUtil.filterNull(limitActionMap.get(or.getLimitAction())));
                maps.put("remark",StringUtil.filterNull(or.getRemark()));
                maps.put("createPerson",StringUtil.filterNull(or.getCreatePerson()));
                maps.put("createTime", or.getCreateTime()==null?"":sdf1.format(or.getCreateTime()));
                data.add(maps);
            }
        }
        ListDataExcelExport export = new ListDataExcelExport();
        String[] cols = new String[]{"id","merchantNo","mobilephone","status","limitAction","remark",
                "createPerson","createTime"
        };
        String[] colsName = new String[]{"ID","商户编号","商户手机号","状态","白名单类型","备注",
                "创建人","创建时间"
        };
        OutputStream ouputStream =null;
        try {
            ouputStream=response.getOutputStream();
            export.export(cols, colsName, data, response.getOutputStream());
        }catch (Exception e){
            log.error("交易限制管理列表失败!",e);
        }finally {
            if(ouputStream!=null){
                ouputStream.close();
            }
        }
    }

    @Override
    public TransLimitWhite selectTransLimitWhiteDetail(Long id){
        return transLimitDao.selectTransLimitWhiteDetail(id);
    }

    @Override
    public int selectTransLimitWhiteMerCount(String merchantNo,String limitAction){
        return transLimitDao.selectTransLimitWhiteMerCount(merchantNo,limitAction);
    }

    @Override
    public int selectTransLimitWhiteMerCountById(String merchantNo,String limitAction,Long id){
        return transLimitDao.selectTransLimitWhiteMerCountById(merchantNo,limitAction,id);
    }

    @Override
    public int insertTransLimitWhite(TransLimitWhite info){
        UserLoginInfo principal = (UserLoginInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        info.setCreatePerson(principal.getUsername());
        return transLimitDao.insertTransLimitWhite(info);
    }

    @Override
    public int updateTransLimitWhite(TransLimitWhite info){
        return transLimitDao.updateTransLimitWhite(info);
    }

    @Override
    public int updateTransLimitWhiteStatus(Integer status,Long id){
        return transLimitDao.updateTransLimitWhiteStatus(status,id);
    }

    @Override
    public int deleteTransLimitWhite(Long id){
        return transLimitDao.deleteTransLimitWhite(id);
    }
}